#include "OrgService.h"

#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include "helper/SessionGuard.h"
#include "dao/OrgDao.h"

OrgService::OrgService(QObject* parent): QObject(parent) {}

QJsonArray OrgService::tree()
{
    // 使用 RAII 守卫自动管理会话
    SessionGuard guard;
    QSqlDatabase db = guard.database();
    const QJsonArray orgArray = OrgDao::getAllOrgList(db);

    if (orgArray.isEmpty())
        return QJsonArray();

    // 使用指针避免节点拷贝
    QHash<QString, std::shared_ptr<QJsonObject>> nodeMap;
    QHash<QString, QJsonArray> childrenMap;  // 预存子节点数组

    // 第一遍：构建节点映射和子节点关系
    for (const QJsonValue & val : orgArray)
    {
        const QJsonObject obj = val.toObject();
        const QString id = obj["id"].toString();

        // 节点指针加入映射
        nodeMap.insert(id, std::make_shared<QJsonObject>(obj));

        // 构建子节点映射关系
        const QString parentId = obj["parentId"].toString();
        if (!parentId.isEmpty() && nodeMap.contains(parentId))
        {
            childrenMap[parentId].append( * nodeMap[id]);
        }
    }

    // 第二遍：构建树形结构
    QJsonArray result;
    for (auto it = nodeMap.begin(); it != nodeMap.end(); ++it)
    {
        const QString id = it.key();
        auto& node = * it.value();

        // 添加子节点
        if (childrenMap.contains(id))
        {
            node["children"] = childrenMap[id];
        }

        // 识别根节点：无父节点或父节点不存在
        const QString parentId = node["parentId"].toString();
        if (parentId.isEmpty() || !nodeMap.contains(parentId))
        {
            result.append(node);
        }
    }

    return result;
}

QJsonObject OrgService::page(QJsonObject sysOrgPageParam)
{
    SessionGuard guard;
    QSqlDatabase db = guard.database();
    return OrgDao::getOrgPage(db, sysOrgPageParam);
}

int  OrgService::deleteByIds(QJsonArray sysOrgIdParamList, bool useFill)
{
    try
    {
        // 使用 RAII 守卫自动管理会话
        SessionGuard guard;
        QSqlDatabase db = guard.database();

        // 开始事务
        guard.beginTransaction(); // 显式开启事务

        int result = 0;

        if (useFill)
        {
            QSet<QString> allIdsSet;

            // 收集所有需要删除的ID
            for (const auto & idValue : sysOrgIdParamList)
            {
                QString id = idValue.toString();
                allIdsSet.insert(id);

                // 添加后代ID
                QStringList descendants = OrgDao::getAllDescendantIds(db, id);
                for (const QString & childId : qAsConst(descendants))
                {
                    allIdsSet.insert(childId);
                }
            }

            qInfo() << "Deleting" << allIdsSet.size() << "organizations (including descendants)";

            // 转换为JSON数组
            QJsonArray deleteArray;
            for (const QString & id : allIdsSet)
            {
                deleteArray.append(id);
            }

            result = OrgDao::removeByIds(db, deleteArray);
        }
        else
        {
            qInfo() << "Deleting" << sysOrgIdParamList.size() << "organizations (without descendants)";
            result = OrgDao::removeByIds(db, sysOrgIdParamList);
        }

        // 提交事务
        guard.commit();

        return result;

    }
    catch (const std::exception& e)
    {
        qCritical() << "Exception in deleteByIds:" << e.what();
        return -1;
    }
}

// 单个删除实现
bool OrgService::deleteById(const QString& id, bool useFill)
{
    QJsonArray idArray;
    idArray.append(id);
    int result = deleteByIds(idArray, useFill);
    return (result > 0);
}
